<template>
  <div class="left-tree">
    <el-input class="filter-input" placeholder="输入关键字进行过滤" v-model="filterText">
    </el-input>
    <el-radio-group v-model="tabData" style="margin-bottom: 10px;" @input="tabChange">
      <el-radio-button label="left">{{leftlabel}}</el-radio-button>
      <el-radio-button label="right">{{rightlabe}}</el-radio-button>
    </el-radio-group>
    <el-tree :data="treeData" :show-checkbox="showCheckbox" default-expand-all node-key="id" ref="tree" highlight-current
      :props="defaultProps" :filter-node-method="filterNode"  @check="handleCheckChange" @node-click="handleNodeClick">
    </el-tree>
  </div>
</template>
<script>
// 有其他页面引用该组件，增加了几个属性
export default {
  name: 'LeftTree',
  props: {
    leftlabel:{
      default: '河流/区域'
    },
    rightlabe:{
      default: '行政区划'
    },
    isDefault:{
      type: String,
      default: ""
    },
    showCheckbox:{
        type: Boolean,
        default: true
    },
    apiConfig:{
        type: Array,
        default: () => []
    },
    defaultProps:{
        default: () => {
            return {
              children: 'children',
              label: 'label'
            }
        }
    },
    isTreeData:{
        type: Boolean,
        default: false
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    treeData: {
        handler() {
            this.$nextTick(() => {
                // treeData 更新完成后的操作
                // 例如：获取当前勾选的节点
                if(this.isDefault){
                  let ids = [];
                  if(this.isDefault == 'all'){
                    ids = this.getTreeId(this.treeData);
                  } else if(this.isDefault == '1'){
                    if(this.treeData[0]){
                       ids = this.getTreeId([this.treeData[0]]);
                    }
                  }
                  if(ids.length){
                    this.$refs.tree.setCheckedKeys(ids);
                    const checkedNodes = this.$refs.tree.getCheckedNodes();
                    this.$emit('tree-check-change', checkedNodes);
                  }
                }

        });
      },
      deep: true
    },
  },
  computed:{
    treeData(){
      return this.tabData == 'left' ? this.leftData : this.rightData;
    }
  },
  data() {
    return {
      filterText: "",
      tabData: "left",
      // treeData: [],
      leftData: [],
      rightData: [],
      defaultSelect:[],
    };
  },
  created() {
    this.getTreeList();
  },
  methods: {
    tabChange(){
      this.getTreeList();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    async  getTreeList(){
        if(this.tabData == 'left' && this.leftData.length > 0){
          return;
        }
        if(this.tabData == 'right' && this.rightData.length > 0){
          return;
        }
        let index = this.tabData == 'left' ? 0 :1;
        let  config = this.apiConfig[index];
        if(config) {
            let {apiFn,apiParams} = config;
            if(apiFn && apiParams) {
                let res = await apiFn(apiParams);
                if(res.code == 200) {
                  let data  = this.convertToTree(res.data || []);
                  if(this.tabData == 'left'){
                    this.leftData = [...data];
                  } else {
                    this.rightData = [...data];
                  }
                }
            }
        }
        
    },

    convertToTree(list) {
        // 创建一个映射表，用于快速查找节点
        if(this.isTreeData){
          return list;
        }
      const map = {};
      const treeData = [];

      // 初始化所有节点
      list.forEach(item => {
        map[item.id] = {
          id: item.id,
          label: item.name,
          ...item,
          children: []
        };
      });

      // 构建树形结构
      list.forEach(item => {
        const node = map[item.id];
        if (item.pId === '0' || !item.pId) {
          // 根节点
          treeData.push(node);
        } else {
          // 子节点
          const parent = map[item.pId];
          if (parent) {
            parent.children.push(node);
          } else {
            // 如果找不到父节点，则作为根节点处理
            treeData.push(node);
          }
        }
      });

      return treeData;
    },
    handleCheckChange() {
      if(this.showCheckbox){
        // 获取所有选中的节点
        const checkedNodes = this.$refs.tree.getCheckedNodes();
        // 发送给父组件
        this.$emit('tree-check-change', checkedNodes);
      }
    },
    handleNodeClick(node){
      if(!this.showCheckbox){
        this.$emit('tree-check-change', [node]);
      }
    },
    getTreeId(list){
      let id = [];
      for(let item of list){
        id.push(item.id);
        if(item.children && item.children.length > 0){
          let cid = this.getTreeId(item.children);
          id = [...id,...cid]
        }
      }
      return id;
    },
  }
}
</script>
<style scoped>
.filter-input {
  margin-bottom: 10px;
}
</style>